package cn.yuanqiao.web.controller.archive.wenjianzhengli;

import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.wenjianzhengli.service.DaiguidangService;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : 庸人一个
 * @create : 2024/4/7 14:16
 */
@RestController
@RequestMapping("/archive/dgd")
public class DaiguidangController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(WenjianzhengliController.class);

    @Autowired
    private DaiguidangService daiguidangService;

    @Autowired
    private ITenantCateMdataListService tenantMdataListService;


    /**
     * 文件整理导出
     * @author gw
     * @param response
     */
    @PreAuthorize("@ss.hasPermi('archive:dgd:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestParam("data1") String data1)
    {
        JSONObject json = JSONObject.parseObject(data1);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        Workbook wb = null;
        try {
            //获取表头以及数据
            String categoryId = json.getString("categoryId");
            String menuId = json.getString("menuId");
            Integer finalType = Integer.valueOf(json.getString("type"));
            List<Map<String, String>> getexportfield = tenantMdataListService.getexportfield(Long.valueOf(categoryId), Long.valueOf(menuId), finalType);
            Map<String, Object> map = daiguidangService.getExportTitleAndBody(json,getexportfield);
            wb = getWorkbookByList((List<String>)map.get("title"),(List<List<String>>)map.get("body"),"sheet",(Map<String, Map<String,String>>)map.get("dict"));
            wb.write(response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
            log.error("导出Excel异常{}", e.getMessage());
        }finally {
            if(wb!=null){
                IOUtils.closeQuietly(wb);
            }
        }
    }
    private static Workbook getWorkbookByList(List<String> title, List<List<String>> body,
                                              String sheetName, Map<String, Map<String,String>> dict) throws Exception{
        //创建HSSFWorkbook对象(excel的文档对象)
        XSSFWorkbook wb = new XSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        XSSFSheet sheet=wb.createSheet(sheetName);
        XSSFRow rowTitle=sheet.createRow(0);
        Map<Integer,Map<String,String>> objectHashMap = new HashMap<>();
        for(int i = 0;i<title.size();i++){
            String s = title.get(i);
            if(dict.containsKey(s)){
                objectHashMap.put(i,dict.get(s));
            }
            rowTitle.createCell(i).setCellValue(title.get(i));
        }
        //创建单元格并设置单元格内容
        for (int i = 0;i<body.size();i++){
            List<String> list = body.get(i);
            XSSFRow rowBody=sheet.createRow(i+1);
            for(int k = 0;k<list.size();k++){
                String s = list.get(k);
                if(!StringUtils.isNotEmpty(s) || "null".equals(s)){
                    s = "";
                }else{
                    if(objectHashMap.containsKey(k)){
                        Map<String, String> map = objectHashMap.get(k);
                        s = map.get(s);
                    }
                }
                rowBody.createCell(k).setCellValue(s);
            }
        }
        return wb;
    }

}
